#include "cJSON/cJSON.h"
#include <stdio.h>
#include <stdlib.h>
#include "log/log.h"

int main(int argc, char const *argv[])
{
    char name[]="zhangsan";
    int age=18;

    //1.将数据转为json字符串
    //创建json对象
    cJSON *root = cJSON_CreateObject();
    //添加键值对key-value
    cJSON_AddStringToObject(root, "name", name);
    cJSON_AddNumberToObject(root, "age", age);
    //将对象转为json字符串
    char *json = cJSON_Print(root);
    log_debug("json:%s",json);

    //2.将json字符串转为json对象
    //解析字符为json对象
    cJSON *root_p = cJSON_Parse(json);
    //获取json对象中的值
    cJSON * name_p = cJSON_GetObjectItem(root_p, "name");
    cJSON * age_p = cJSON_GetObjectItem(root_p, "age");
    //判断是否获取到
    if(name_p == NULL && age_p == NULL){
        log_error("get json error");
        return -1;
    }
    log_debug("name:%s,age:%d",name_p->valuestring,age_p->valueint);

    //3.释放内存（因为创建字符传用的melloc）
    cJSON_Delete(root);
    cJSON_Delete(root_p);
    free(json);

    return 0;
}


